/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa165.library.web_layer;

import cz.muni.fi.pa165.library.web_layer.adminPages.Book.ShowAllBook;
import cz.muni.fi.pa165.library.web_layer.readerPages.ShowAllBookReader;
import org.apache.wicket.Session;
import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.mapper.parameter.PageParameters;

/**
 *
 * @author dulinka
 */
public class Login extends Template {

    private static final long serialVersionUID = 1L;
    private TextField userIdField;
    private PasswordTextField passField;
    private Form form;

    public Login(final PageParameters parameters) {
        super(parameters);
        add(new BookmarkablePageLink("homeLink", HomePage.class));

        userIdField = new TextField("userId", new Model(""));
        passField = new PasswordTextField("password", new Model(""));

        /* Make sure that password field shows up during page re-render **/

        passField.setResetPassword(false);

        form = new LoginForm("loginForm");
        form.add(userIdField);
        form.add(passField);
        add(form);
    }

    class LoginForm extends Form {

        public LoginForm(String id) {
            super(id);
        }

        @Override
        public void onSubmit() {
            String userId = Login.this.getUserId();
            String password = Login.this.getPassword();
            AuthenticatedWebSession session = (AuthenticatedSession) getSession();
            if (session.authenticate(userId, password)) {
                AuthenticatedSession session2 = ((AuthenticatedSession) Session.get());
                if (session2.getCheckAdmin()) {
                    setResponsePage(ShowAllBook.class);
                } else {
                    setResponsePage(ShowAllBookReader.class);
                }
            }

        }
    }

    protected String getUserId() {
        return userIdField.getDefaultModelObjectAsString();
    }

    protected String getPassword() {
        return passField.getDefaultModelObjectAsString();
    }
}
